package com.chen.authority.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.authority.common.model.PageQo;
import com.chen.authority.common.response.Response;
import com.chen.authority.common.util.WrapperUtil;
import com.chen.authority.mapper.DictDataMapper;
import com.chen.authority.model.dto.DictDataDto;
import com.chen.authority.model.po.DictDataPo;
import com.chen.authority.model.qo.DictDataQo;
import com.chen.authority.model.vo.DictDataVo;
import com.chen.authority.service.DictDataService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典数据 Service业务层处理
 *
 * @author chengy
 * @date 2023-09-04
 */
@Service
public class DictDataServiceImpl extends ServiceImpl<DictDataMapper, DictDataPo> implements DictDataService {

    @Override
    public Page<DictDataVo> pageQueryDictDataList(PageQo pageQo, DictDataQo dictDataQo) {
        return baseMapper.selectVoPage(pageQo.build(), WrapperUtil.buildQueryWrapper(dictDataQo));
    }

    @Override
    public Response addOrUpdateDictData(Integer id, DictDataDto dto) {
        boolean exists = baseMapper.exists(Wrappers
                .<DictDataPo>lambdaQuery()
                .eq(DictDataPo::getLabel, dto.getLabel())
                .ne(ObjectUtil.isNotNull(id), DictDataPo::getId, id));
        if (exists) {
            return Response.fail("标签重复，请检查");
        }
        DictDataPo dictData = dto.toPo(DictDataPo.class);
        dictData.setId(id);
        return this.saveOrUpdate(dictData) ? Response.success() : Response.fail();
    }

    @Override
    public List<DictDataVo> findDictDataList(QueryWrapper<DictDataPo> queryWrapper) {
        return baseMapper.selectVoList(queryWrapper);
    }

}